package com.dpj.test;

import ch.qos.logback.core.joran.conditional.ThenAction;
import lombok.extern.slf4j.Slf4j;

//两阶段终止模式(优雅的终止)
@Slf4j(topic = "c.TwoPhaseDemo")
public class TwoPhaseDemo {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt=new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);
        tpt.stop();

    }


}
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination{
    private Thread monitor;
    //启动监控线程
    public void start(){
        monitor=new Thread(()->{
            while (true){
                Thread thread = Thread.currentThread();
                if(thread.isInterrupted()){
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);//情况1(运行到此处被打断，因为处于睡眠状态，所以我们的打断会被catch捕获处理处理，相当于没打断，所以返回为false)
                    log.debug("执行监控记录");//情况2(运行到此处被打断,数据正常被打断，所以会返回true,退出循环)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标记
                   // thread.interrupt();
                }
            }
        });
        monitor.start();
    }
    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }
}

